package cn.edu.swu.zwy.db;

import cn.edu.swu.zwy.book.Book;
import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.ArrayList;

public class DBTool {
    private static BasicDataSource dataSource;

    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            dataSource=new BasicDataSource();
            dataSource.setUrl("jdbc:mysql://localhost:3306/bookstore");
            dataSource.setUsername("root");
            dataSource.setPassword("zwy041206");

            dataSource.setMinIdle(5);
            dataSource.setMaxIdle(7);
            dataSource.setMaxTotal(20);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    protected DBTool(){
    }


    public static Connection getDBConnection() throws SQLException {
        return dataSource.getConnection();
    }

    protected boolean execute(String cudSQL) throws SQLException {
        try(Connection connection=dataSource.getConnection()){
            try(Statement statement=connection.createStatement()){
                return statement.execute(cudSQL);
            }
        }
    }

    // 提供一个执行查询的帮助接口
    protected void query(String sql, ResultSetVisitor visitor) throws SQLException {
        System.out.println(sql);
        try(Connection connection = dataSource.getConnection()) {
            try(Statement statement = connection.createStatement()) {
                try(ResultSet resultSet = statement.executeQuery(sql)) {
                    while (resultSet.next()) {
                        visitor.visit(resultSet);
                    }
                }
            }
        }
    }



}
